package demo.servicemix.cxf;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Date;

import javax.xml.bind.JAXBContext;

public class JAXBText {
	public static void objectToXml(Object obj, String file) throws Exception {
		OutputStream output = null;
		try {
			JAXBContext context = JAXBContext.newInstance(obj.getClass());
			output = new FileOutputStream(file);
			context.createMarshaller().marshal(obj, output);
			output.flush();
		} finally {
			if (output != null) {
				try {
					output.close();
				} catch (Exception e) {
				}
			}
		}
	}

	@SuppressWarnings("unchecked")
	public static <T> T xmlToObject(Class<T> clazz, String file) throws Exception {
		InputStream input = null;
		try {
			JAXBContext context = JAXBContext.newInstance(clazz);
			input = new FileInputStream(file);
			return (T) context.createUnmarshaller().unmarshal(input);
		} finally {
			if (input != null) {
				try {
					input.close();
				} catch (Exception e) {
				}
			}
		}
	}

	public static void printFile(String file) throws Exception {
		InputStreamReader input = null;
		try {
			input = new FileReader(file);
			StringBuilder sb = new StringBuilder();
			char[] buf = new char[1024];
			int length = -1;
			while ((length = input.read(buf)) != -1) {
				sb.append(buf, 0, length);
			}
			System.out.println(sb);
		} finally {
			if (input != null) {
				try {
					input.close();
				} catch (Exception e) {
				}
			}
		}
	}

	public static void main(String[] args) throws Exception {
		String file = "target/book.xml";
		Book book = new Book();
		book.setId(121);
		book.setName("hello");
		book.setAuthor("hzp1");
		book.setUpdateDate(new Date());

		objectToXml(book, file);
		
		printFile(file);

		System.out.println(xmlToObject(Book.class, file));

	}
}
